#!/usr/bin/env python2
#-*- coding: utf-8 -*-


import traceback
from Ump.objs.session_wrapper import _sw
from Ump import utils
from Ump.common import log
from Ump.objs.db import models
from Ump.common import exception
from Ump.objs.session_wrapper import enable_log_and_session
from Ump.objs.manager_base import Manager
from Ump.objs.volume.manager import VolumeManager
from sqlalchemy import and_

LOG = log.get_log('Ump.objs.qos.manager')


@models.add_model(models.QOS)
class QOSManager(Manager):

    def __init__(self):
        super(QOSManager, self).__init__()
        self.vom = VolumeManager()

    def _check_double_name(self, user_id, name):
        print  user_id
        print  name
        #qoses = _sw.get_one(model=models.QOS, id_or_spec={'user_id': user_id, 'name': name})
        qoses = models.QOS.query.filter(and_(models.QOS.name == name, models.QOS.user_id == user_id)).first()
        if qoses:
            raise Exception("指定的名称已被使用")

    @enable_log_and_session(resource='qos', event='create')
    def create(self, _logger, params):
        name = params['name']

        _logger.update_props(oplog_obj=name)

        qos = self._create(**params)
        return qos

    def _create(self, name,
                throt_iops_avg=None, throt_burst_iops_max=None, throt_burst_iops_time=None,
                throt_mbps_avg=None, throt_burst_mbps_max=None, throt_burst_mbps_time=None,
                username='admin', **kwargs):

        user = _sw.get_user(username=username)
        if not user:
            raise exception.UserNotFound(username=username)

        self._check_double_name(user.id, name)
        values = {
            'name': name,
            'user_id': user.id,
            'throt_iops_avg': throt_burst_iops_max,
            'throt_burst_iops_max': throt_burst_iops_max,
            'throt_burst_iops_time': '0',
            'throt_mbps_avg': throt_burst_mbps_max,
            'throt_burst_mbps_max': throt_burst_mbps_max,
            'throt_burst_mbps_time': '0',
        }

        qos = models.QOS(values).save()
        return qos

    @enable_log_and_session(resource='qos', event='delete')
    def delete(self, _logger, params):
        qos = None
        if params.get('id'):
            qos = models.QOS.query.filter_by(id=params['id']).first()

        if params.get('name'):
            qos = models.QOS.query.filter_by(name=params['name']).first()

        if not qos:
            raise exception.NotFound()

        _logger.update_props(oplog_obj=qos.name)

        if qos.volumes:
            raise Exception("QoS(%s)已经被卷使用，不可删除" % qos.name)

        return qos.delete()

    @enable_log_and_session(resource='qos', event='update')
    def update(self, _logger, params):
        qos = None
        if params.get('id'):
            qos = models.QOS.query.filter_by(id=params['id']).first()

        if params.get('name'):
            qos = models.QOS.query.filter_by(name=params['name']).first()

        if not qos:
            raise exception.NotFound()

        _logger.update_props(oplog_obj=qos.name)

        qos = self._update(qos, **params)
        return qos

    def _update(self, qos, name=None,
                throt_iops_avg=None, throt_burst_iops_max=None, throt_burst_iops_time=None,
                throt_mbps_avg=None, throt_burst_mbps_max=None, throt_burst_mbps_time=None,
                **kwargs):
        values = {}

        if name:
            if name != qos.name:
                self._check_double_name(qos.user_id, name)
                utils.update_values(values, 'name', name)

        utils.update_values(values, 'throt_iops_avg', throt_burst_iops_max)
        utils.update_values(values, 'throt_burst_iops_max', throt_burst_iops_max)
        utils.update_values(values, 'throt_burst_iops_time', '0')

        utils.update_values(values, 'throt_mbps_avg', throt_burst_mbps_max)
        utils.update_values(values, 'throt_burst_mbps_max', throt_burst_mbps_max)
        utils.update_values(values, 'throt_burst_mbps_time', '0')

        qos.update(values)

        # TODO
        volumes = _sw.get_list(models.Volume, spec=dict(qos_id=qos.id))
        for volume in volumes: 
            self.vom._update(volume, qos_id=volume.qos_id)
        return qos
